package com.hui.account.activity;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hui.account.R;
import com.hui.account.database.SQLManage;
import com.hui.account.entity.FileEntity;
import com.hui.account.entity.RecordEntity;
import com.hui.account.entity.UserEntity;
import com.hui.account.utils.ButtonUtils;
import com.hui.account.utils.CommonUtils;
import com.hui.account.utils.ImageUtils;
import com.hui.account.utils.ToastUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 编辑客户
 */
public class UserModActivity extends AppCompatActivity implements View.OnClickListener {

    Context context;

    Button backBtn, saveBtn, modBtn, delBtn;

    TextView recordText; // 客户欠款单数量

    LinearLayout recordImage; // 跳转到客户欠款详情页

    EditText userNameEdit, phoneEdit, remarkEdit;

    UserEntity user; // 本次要编辑编辑的客户信息

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getApplicationContext();
        setContentView(R.layout.activity_user_mod);

        // 1、设置屏幕顶部字体颜色
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        // 2、初始化页面
        initView();

        SharedPreferences sharedPreferences = getSharedPreferences("shareParam", Context.MODE_PRIVATE);
        String value = sharedPreferences.getString("selectUser", "");
        if (!TextUtils.isEmpty(value)) {
            user = new Gson().fromJson(value, UserEntity.class);
            phoneEdit.setText(user.getPhone());
            remarkEdit.setText(user.getRemark());
            userNameEdit.setText(user.getUserName());

            // 计算客户欠款单数量
            List<RecordEntity> list = SQLManage.getUserRecords(0, 0, user.getId());
            if (list.size() > 0) {
                recordText.setText("当前有" + list.size() + "条欠款记录");
            }
        } else {
            ToastUtils.error(context, "客户信息获取失败", Gravity.CENTER, 0, 0);
            finish();
        }
    }

    /**
     * 初始化页面
     */
    @SuppressLint("WrongViewCast")
    private void initView() {
        modBtn = findViewById(R.id.user_mod);
        delBtn = findViewById(R.id.user_del);
        backBtn = findViewById(R.id.user_mod_back);
        saveBtn = findViewById(R.id.user_mod_save);
        phoneEdit = findViewById(R.id.user_mod_phone);
        remarkEdit = findViewById(R.id.user_mod_remark);
        userNameEdit = findViewById(R.id.user_mod_name);
        recordText = findViewById(R.id.user_mod_record);
        recordImage = findViewById(R.id.user_mod_change);

        // 默认点击监听
        modBtn.setOnClickListener(this);
        delBtn.setOnClickListener(this);
        backBtn.setOnClickListener(this);
        saveBtn.setOnClickListener(this);
        recordImage.setOnClickListener(this);
    }

    /**
     * Activity加载时执行
     */
    @Override
    protected void onResume() {
        super.onResume();

        flushData();
    }

    /**
     * 刷新数据
     */
    @SuppressLint("SetTextI18n")
    private void flushData() {
        List<RecordEntity> list = SQLManage.getUserRecords(0, 0, user.getId());
        if (list.size() > 0) {
            recordText.setText("当前有" + list.size() + "条欠款记录");
        } else {
            recordText.setText("暂无欠款账单");
        }
    }

    /**
     * 弹出删除提示框
     */
    private void showDel() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("确定删除").setMessage("是否确认删除该客户？").setNegativeButton("取消", null).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                // 1、删除客户账单数据
                List<RecordEntity> list = SQLManage.getUserRecords(0, 0, user.getId());
                if (list.size() > 0) {
                    ToastUtils.error(context, "无法删除，该客户欠款尚未结清！", Gravity.BOTTOM, 0, 300);
                    return;
                }

                // 2、查询客户全部账单，删除图片
                List<RecordEntity> records = SQLManage.getUserRecords(1, null, user.getId());
                if (records.size() > 0) {
                    List<String> images = records.stream().map(RecordEntity::getImageName).collect(Collectors.toList());
                    List<FileEntity> files = SQLManage.getFilesByName(images);
                    if (files.size() > 0) {
                        for (FileEntity file : files) {
                            SQLManage.delFile(file.getId());
                            ImageUtils.delDiskFile(file.getPath());
                        }
                    }
                }

                // 3、删除客户全部账单
                SQLManage.deleteUserRecords(user.getId());

                // 4、删除客户数据
                SQLManage.delUser(user.getId());
                ToastUtils.success(context, "删除成功", Gravity.CENTER, 0, 0);
                finish();
            }
        });
        builder.create().show();
    }

    /**
     * 修改客户
     */
    private void modUser() {
        String userName = userNameEdit.getText().toString().trim();
        if (TextUtils.isEmpty(userName)) {
            ToastUtils.error(this, "【必填项】请输入客户姓名！", Gravity.CENTER, 0, 120);
            return;
        }

        if (userName.contains(CommonUtils.SPLIT)) {
            ToastUtils.error(this, "不允许使用特殊字符【" + CommonUtils.SPLIT + "】", Gravity.CENTER, 0, 120);
            return;
        }

        // 校验客户姓名是否重复
        UserEntity entity = SQLManage.getUserById(user.getId());
        if (null == entity) {
            ToastUtils.error(this, "获取客户信息失败", Gravity.CENTER, 0, 120);
            return;
        }
        if (!userName.equals(entity.getUserName()) && null != SQLManage.getUserByName(userName)) {
            ToastUtils.error(this, "该客户已存在！", Gravity.CENTER, 0, 120);
            return;
        }

        entity.setUserName(userName);

        String phone = phoneEdit.getText().toString().trim();
        if (!TextUtils.isEmpty(phone))
            entity.setPhone(phone);

        String remark = remarkEdit.getText().toString().trim();
        if (!TextUtils.isEmpty(remark))
            entity.setRemark(remark);

        // 修改客户
        SQLManage.modUser(entity);
        ToastUtils.success(this, "编辑成功", Gravity.CENTER, 0, 0);
        finish();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.user_mod_back:
                finish();
                break;
            case R.id.user_mod_change:
                if (!ButtonUtils.isFastDoubleClick() && !"暂无欠款账单".equals(recordText.getText().toString())) {
                    startActivity(new Intent(this, UserRecordActivity.class));
                }
                break;
            case R.id.user_mod:
                if (!ButtonUtils.isFastDoubleClick()) {
                    // 设置 EditText可编辑
                    phoneEdit.setEnabled(true);
                    remarkEdit.setEnabled(true);
                    userNameEdit.setEnabled(true);
                    saveBtn.setVisibility(View.VISIBLE);
                    ToastUtils.success(context, "已进入编辑模式", Gravity.CENTER, 0, 300);
                }
                break;
            case R.id.user_del:
                if (!ButtonUtils.isFastDoubleClick())
                    showDel();

                break;
            case R.id.user_mod_save:
                if (!ButtonUtils.isFastDoubleClick())
                    modUser();

                break;
        }
    }
}